##############################################################################

library(optparse)
library(data.table)

##############################################################################

inputpar <- commandArgs(TRUE)

if(1!=1){
  inputpar <- c()
  inputpar[1] <- "S48"
  inputpar[2] <- "~/20220915_gastric_multiple/dna_combine/titan/maf"
  inputpar[3] <- "~/20220915_gastric_multiple/dna_combine/config/tumor_normal.list"
  inputpar[4] <- "~/20220915_gastric_multiple/dna_combine/titan/mut"
}

Tumor <- inputpar[1]
maf_path <- inputpar[2]
sample_file <- inputpar[3]
out_path <- inputpar[4]

##############################################################################

info<- data.frame(fread(sample_file, header=F) )
colnames(info) <- c("Tumor" , "Normal")

##############################################################################

Normal <- info[info$Tumor==Tumor,"Normal"]

res <- data.frame()

maf_file <- paste0( maf_path , "/" , Tumor , "_" , Normal , ".maf" )
dat <- data.frame(fread(maf_file , quote=""))

tmp <- dat[,c("Chromosome" , "Start_Position" , "End_Position" , "Hugo_Symbol" ,
"Reference_Allele" , "Tumor_Seq_Allele2" , 
"Variant_Classification" , "t_alt_count" , "t_ref_count" )]

tmp$depth <- tmp$t_alt_count + tmp$t_ref_count
tmp$vaf <- tmp$t_alt_count / tmp$depth 

tmp <- data.frame(
    Chr = tmp$Chromosome , Start_Position = tmp$Start_Position , End_Position = tmp$End_Position ,
    REF = tmp$Reference_Allele , ALT = tmp$Tumor_Seq_Allele2 , Hugo_Symbol = tmp$Hugo_Symbol ,
    Variant_Classification = tmp$Variant_Classification , cover = tmp$depth , freq = tmp$vaf
  )

tmp$ID <- paste( tmp$Chr , tmp$Start_Position , tmp$End_Position , tmp$REF , tmp$ALT , sep = ":" )

out_file <- paste0( out_path , "/" , Tumor , "_Mut.tsv")
write.table(tmp,out_file,sep="\t",quote=F)